﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sausage.Common;
using Sausage.Web.Code;
using Sausage.Web.DataModel;
using Sausage.Web.Models;
using Telerik.Web.Mvc;

namespace Sausage.Web.Domain
{
	public class EmergencyReactionHelper
	{
		public static void CreateEmergencyReaction(EmergencyReactionListRow data)
		{
			using (var context = new SausageEntities())
			{
				var entity = new EmergencyReaction()
								 {
									 ReactionID = Guid.NewGuid(),
									 PostDate = data.PostDate,
									 Poster = Helper.CurrentPrincipal.User.UserName,
									 ReactionLevel = data.ReactionLevel,
									 AlarmLevel = data.AlarmLevel,
									 WeatherWarning = data.WeatherWarning,
									 WeatherWarningUrl = data.WeatherWarningUrl,
									 ExpireDuration = data.ExpireDuration,
									 ExpireDate = data.PostDate.AddHours(data.ExpireDuration)
								 };

				context.AddToEmergencyReaction(entity);
				context.SaveChanges();
			}
		}

		public static void DeleteEmergencyReaction(Guid reactionID)
		{
			using (SausageEntities context = new SausageEntities())
			{
				var entity = context.EmergencyReaction.FirstOrDefault(item => item.ReactionID == reactionID);
				if (null != entity)
				{
					context.DeleteObject(entity);
					context.SaveChanges();
				}
			}
		}

		public static GridModel<object> Select(JosnPagingQueryModel query)
		{
			using (var context = new SausageEntities())
			{
				if (query.SortModel.Length == 0) //default sort.
					query.SortModel = new JosnQuerySortModel[] { new JosnQuerySortModel() { property = "PostDate", direction = "DESC" } };

				return
					QueryEmergencyReaction(
						context.EmergencyReaction,
						query);
			}
		}

		private static GridModel<object> QueryEmergencyReaction(IQueryable<EmergencyReaction> source,
																JosnPagingQueryModel query)
		{
			var result = UIHelper.GetGridModelFromQueryModel<EmergencyReaction>(
				source,
				query.page,
				query.limit,
				GetSortDescriptorFromQueryModel(query.SortModel),
				GetSearchFilterFromQueryModel(query.FilterModel));

			var list = result.Data.Select(item => new
													  {
														  item.ReactionID,
														  item.WeatherWarning,
														  item.WeatherWarningUrl,
														  item.ReactionLevel,
														  item.Poster,
														  item.PostDate,
														  item.ExpireDate,
														  item.ExpireDuration
													  }).ToList();

			return new GridModel<object>()
					   {
						   Aggregates = result.Aggregates,
						   Data = list,
						   Total = result.Total
					   };
		}

		private static List<IFilterDescriptor> GetSearchFilterFromQueryModel(
			IEnumerable<JosnQueryFilterModel> filterModels)
		{
			var filterList = new List<IFilterDescriptor>();
			foreach (var item in filterModels)
			{
				if (string.IsNullOrEmpty(item.value))
					continue;

				if (item.property.EndsWith("ID", StringComparison.InvariantCultureIgnoreCase))
				{
					var targetID = Guid.Parse(item.value);
					if (targetID != Guid.Empty)
						filterList.Add(new FilterDescriptor(item.property, FilterOperator.IsEqualTo, targetID));
				}
				else //other filter.
					filterList.Add(new FilterDescriptor(item.property, FilterOperator.Contains, item.value));
			}
			return filterList;
		}

		private static List<SortDescriptor> GetSortDescriptorFromQueryModel(IEnumerable<JosnQuerySortModel> sortModels)
		{
			//convert the sort description.
			var sortList = new List<SortDescriptor>();
			foreach (var item in sortModels)
			{
				var descriptor = new SortDescriptor()
									 {
										 Member = item.property,
										 SortDirection =
											 item.direction.ToLower() == "desc"
												 ? ListSortDirection.Descending
												 : ListSortDirection.Ascending
									 };

				if (descriptor.Member == "Organization")
					descriptor.Member = "Organization.OrganizationName";

				sortList.Add(descriptor);
			}
			return sortList;
		}

		public static EmergencyReaction GetLastestEmergencyReaction()
		{
			using (SausageEntities context = new SausageEntities())
			{
				return context.EmergencyReaction.Where(item => (item.PostDate <= DateTime.Now && item.ExpireDate.HasValue && DateTime.Now <= item.ExpireDate.Value)).OrderByDescending(item => item.PostDate).FirstOrDefault();
			}
		}
	}
}
